const { getDocData } = require("../../../../db");
const { util, BaseErr } = require("utils");
const { TokenStatus, GetTokenType } = require("../../../../constEnum");
const During = 500;
const MaxRetry = 3;
// 每个 300ms 检查一次
async function retryGetDoc(docId) {
    let retry = 0;
    let err = undefined;
    let data = undefined;

    while (retry < MaxRetry) {
        await util.delay(During);
        retry = retry + 1;
        let [doc_err, doc_data] = await getDocData(docId);
        if (!util.nilValue(doc_err)) {
            err = doc_err;
            data = undefined;
            break;
        }
        // 有数据了
        // 检查状态
        let { tokenStatus } = doc_data || {};
        if (tokenStatus !== TokenStatus.loading) {
            err = undefined;
            data = doc_data;
            break;
        }
    }

    // 判断是不是 没有 拿到 token
    if (util.nilValue(err)) {
        if (util.nilValue(data)) {
            err = new BaseErr(-5003, "获取token失败");
        }
    }
    return [err, data];
}

async function handleLoading(docId) {
    let [wait_err, wait_data] = await retryGetDoc(docId);
    if (!util.nilValue(wait_err)) {
        return [wait_err, null];
    }
    // 返回 这样的结果
    let res = {
        flag: true,
        message: "获取成功",
        doc: wait_data,
        type: GetTokenType.cache,
    };
    return [null, res];
}

module.exports = {
    handleLoading,
};
